// app.ts
// 引入微信小程序类型
type NavigateToOptions = WechatMiniprogram.NavigateToOption;
type RedirectToOptions = WechatMiniprogram.RedirectToOption;
type SwitchTabOptions = WechatMiniprogram.SwitchTabOption;

App({
  globalData: {},

  onLaunch() {
    this.interceptRoute();
    this.checkLoginStatus();
    this.interceptRequest(); // 初始化请求拦截

    // 原有本地存储逻辑
    const logs = wx.getStorageSync('logs') || [];
    logs.unshift(Date.now());
    wx.setStorageSync('logs', logs);

    // 原有登录逻辑
    wx.login({
      success: res => {
        console.log(res.code);
      }
    });
  },

  // 全局路由拦截
  interceptRoute() {
    const originalNavigateTo = wx.navigateTo;
    const originalRedirectTo = wx.redirectTo;
    const originalSwitchTab = wx.switchTab;

    wx.navigateTo = (options: NavigateToOptions) => {
      if (this.checkPagePermission(options.url)) {
        originalNavigateTo(options);
      }
    };

    wx.redirectTo = (options: RedirectToOptions) => {
      if (this.checkPagePermission(options.url)) {
        originalRedirectTo(options);
      }
    };

    wx.switchTab = (options: SwitchTabOptions) => {
      if (this.checkPagePermission(options.url)) {
        originalSwitchTab(options);
      }
    };
  },

  // 检查页面权限
  checkPagePermission(pageUrl: string): boolean {
    const pageRoleMap: Record<string, string[]> = {
      '/pages/admin/admin': ['ADMIN'],
      '/pages/admin/user-manage': ['ADMIN'],
      '/pages/merchant/center': ['MERCHANT'],
      '/pages/user/index': ['USER', 'ADMIN']
    };

    const publicPages = ['/pages/login/login', '/pages/index/index'];
    if (publicPages.includes(pageUrl)) {
      return true;
    }

    const requiredRoles = pageRoleMap[pageUrl];
    if (!requiredRoles) {
      wx.showToast({ title: '无权限访问此页面', icon: 'none' });
      return false;
    }

    const userRoles = wx.getStorageSync('userRoles') || [];
    const hasPermission = requiredRoles.some((role: string) => userRoles.includes(role));
    if (!hasPermission) {
      wx.showToast({ title: '您的角色无权限访问', icon: 'none' });
      wx.redirectTo({ url: '/pages/login/login' });
      return false;
    }

    return true;
  },

  // 检查登录状态
  checkLoginStatus() {
    const token = wx.getStorageSync('jwtToken');
    const userRoles = wx.getStorageSync('userRoles');

    if (token && userRoles.length > 0) {
      if (userRoles.includes('ADMIN')) {
        wx.redirectTo({ url: '/pages/admin/admin' });
      } else if (userRoles.includes('MERCHANT')) {
        wx.redirectTo({ url: '/pages/merchant/center' });
      } else {
        wx.switchTab({ url: '/pages/user/index' });
      }
    } else {
      wx.redirectTo({ url: '/pages/login/login' });
    }
  },

  // 请求拦截
  interceptRequest() {
    const originalRequest = wx.request;
    wx.request = function <T = any>(options: WechatMiniprogram.RequestOption<T>): WechatMiniprogram.RequestTask {
      const token = wx.getStorageSync('jwtToken');
      if (token) {
        options.header = options.header || {};
        options.header.Authorization = `Bearer ${token}`;
      }
  
      // 保存原始success和fail回调
      const originalSuccess = options.success;
      const originalFail = options.fail;
  
      // 重写success回调：处理HTTP状态码（401/403在这里判断）
      options.success = (res) => {
        // 处理401（Token过期）
        if (res.statusCode === 401) {
          wx.removeStorageSync('jwtToken');
          wx.removeStorageSync('userRoles');
          wx.showToast({ title: '登录已过期，请重新登录', icon: 'none' });
          wx.redirectTo({ url: '/pages/login/login' });
          return; // 阻止后续逻辑
        }
  
        // 处理403（权限不足）
        if (res.statusCode === 403) {
          wx.showToast({ title: '权限不足，无法操作', icon: 'none' });
          wx.navigateBack();
          return; // 阻止后续逻辑
        }
  
        // 正常情况，执行原始success回调
        if (originalSuccess) originalSuccess(res);
      };
  
      // 重写fail回调：仅处理网络错误（无statusCode）
      options.fail = (err) => {
        wx.showToast({ title: '网络错误，请检查网络', icon: 'none' });
        if (originalFail) originalFail(err); // 执行原始fail回调
      };
  
      return originalRequest(options);
    };
  }
}
);